<?php

namespace app\api\model;

use think\Model;
use think\model\concern\SoftDelete;

class MemberBill extends ApiModel
{
    // 表名
    protected $name = 'member_bill';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;


    // 追加属性
    protected $append = [

    ];

//    public function getRetailTypeAttr($value)
//    {
//        $status = [1 => '间推', 2 => '直推'];
//        return $status[$value];
//
//    }


    public function getAdviseRecommend($params)
    {
        $member_id = $params['uid'];
        $member = (new MemberModel())->where(['id' => $member_id])->field('id,advise_qrcode,advise_total_money')->find();
        $member['advise_qrcode'] = (new MemberModel())->createImg($member['advise_qrcode']);
        $member['recommend_nums'] = (new MemberModel())->where(['pid' => $member_id, 'source' => 2])->select()->count();
        return $this->api_success('获取成功', $member);
    }


    public function getAdviseBillList($params)
    {
        $recommend = (new MemberModel())
            ->where('source', 2)
            ->where(function ($query) use ($params) {
                $query->where('pid', $params['uid'])
                    ->whereOr('ppid', $params['uid']);
            })
            ->field('id, pid, ppid, nickname, avatar, create_time')
            ->paginate(10);

        //查询消费分销
        foreach ($recommend as $key => &$value) {
            //查询收入
            $memberBillIncome = (new MemberBill())->where(['retail_member_id' => $value['id'], 'member_id' => $params['uid'],'type'=>1])->sum('income');
            $value['income'] = $memberBillIncome;
            if ($value['pid'] > 0) {
                $value['retail_name'] = '间推';
            } else {
                $value['retail_name'] = '直推';
            }
            unset($value['pid']);
            unset($value['ppid']);
        }

        return $this->api_success('获取成功', $recommend);
    }


    public function getAdviseIncomeList($params = array()){

        $member_id = $params['uid'];
        $recommend = (new MemberBill())
            ->alias('b')
            ->leftJoin('member m', 'm.id = b.retail_member_id')
            ->field('b.id,b.retail_type,b.retail_member_id,m.nickname,m.avatar,m.create_time,income as income')
            ->where(['b.member_id' => $member_id,'b.type'=>2])
            ->order('id desc')
            ->paginate(10);


        foreach ($recommend as &$val) {
            if($val['retail_type'] == 1){
                $val['retail_name'] = '间推';
            }else{
                $val['retail_name'] = '直推';
            }
        }

        return $this->api_success('获取成功',$recommend);
    }


}
